var server = {};

function InstallFunction(obj, functionName) {
    obj[functionName] = function() { request(functionName, arguments); }
}

//Request class based on the AJAX Google App Engine tutorial
function request(function_name, opt_argv) {
    if (!opt_argv)
        opt_argv = new Array();

    // Find if the last arg is a callback function; save it
    var callback = null;
    var len = opt_argv.length;
    if (len > 0 && typeof opt_argv[len-1] == 'function') {
        callback = opt_argv[len-1];
        opt_argv.length--;
    }
    var async = (callback != null);

    // Encode the arguments in to a URI
    var query = 'action=' + encodeURIComponent(function_name);
    for (var i = 0; i < opt_argv.length; i++) {
        var key = 'arg' + i;
        var val = JSON.stringify(opt_argv[i]);
        query += '&' + key + '=' + encodeURIComponent(val);
    }
    query += '&time=' + new Date().getTime(); // IE cache workaround

    // Create an XMLHttpRequest 'GET' request w/ an optional callback handler 
    var req = new XMLHttpRequest();
    req.open('GET', '/adminrpc?' + query, async);
    
    if (async) {
        req.onreadystatechange = function() {
            if(req.readyState == 4 && req.status == 200) {
                var response = null;
                try {
                    response = JSON.parse(req.responseText);
                } catch (e) {
                    response = req.responseText;
                }
                callback(response);
            }
        }
    }

    // Make the actual request
    req.send(null);
}

function resetSerie(){
    serie = $("#comboReset option:selected").text();
    if(serie.length > 0){
        $('#notification').jGrowl("<b>LOADING...</b>");
        server.ResetSerie(serie, resetComplete);
    }
}

function resetComplete(serie){
    if(serie.length > 0){
        $('#notification').jGrowl("<b>"+serie+": RESET COMPLETE</b>");
    }
}

function sendMessage(){
    var message = $("#textMessage").val();
    $('#notification').jGrowl("<b>SENDING...</b>");
    server.SendMessage(message);
}
